package middleware

import (
	"fmt"
	"ginEssential/common"
	"ginEssential/model"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		// get authorization header
		tokenString := ctx.GetHeader("Authorization")
		fmt.Println(tokenString)
		// validate token format
		if tokenString == "Bearer" || tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "token格式错误"})
			ctx.Abort()
			return
		}

		tokenString = tokenString[7:]

		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "token格式错误2"})
			ctx.Abort()
			return
		}

		// 验证通过后获取claim中的userId
		userId := claims.UserId
		DB := common.GetDB()
		var user model.User
		DB.First(&user, userId)

		// 用户是否存在
		if user.ID == 0 {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "用户不存在"})
			ctx.Abort()
			return
		}

		// token过期
		isExpired := common.IsTokenExpired(claims)
		if isExpired {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 402, "msg": "登录已失效"})
			ctx.Abort()
			return
		}

		// 若存在
		ctx.Set("user", user)

		ctx.Next()

	}
}
